<template>
  <div id="RoomTypeSetting">
    <div class="content">
      <div class="overflow-auto">
        <div class="right">
          <div class="add">
            <el-button type="primary" @click="add"> 新增房型 </el-button>
          </div>
          <div class="table">
            <el-table :data="tableData" style="width: 100%" min-height="250" :max-height="tableMaxHeight"
              :header-cell-style="{ background: '#F7F8FB' }">
              <el-table-column fixed prop="pms_title" label="房型名称" width="250">
              </el-table-column>
              <el-table-column prop="pms_sort_title" label="简称" width="120">
              </el-table-column>
              <el-table-column prop="pms_uniform_price" label="默认价" width="120">
              </el-table-column>
              <el-table-column prop="pms_weekend_price" label="区分价" width="120">
                <template slot-scope="scope">
                  <div>
                    <span>平日</span><span>{{ scope.row.pms_weekend_price }}</span>
                  </div>
                  <div>
                    <span>周末</span><span>{{ scope.row.pms_weekday_price }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="房间数" width="120" align="center">
              </el-table-column>
              <el-table-column label="房间号">
                <template slot-scope="props">
                  <span style="margin-right: 10px" v-for="item in props.row.hotel_room_num" :key="item.id">
                    {{ item.room_num }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="zip" label="操作" width="120">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-divider direction="vertical"></el-divider>
                  <el-button size="size" type="text" style="color: red" @click="handleDelete(scope.$index, scope.row)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="centerDialogVisible" width="30%" :before-close="closed" center>
      <template slot="title">
        <div style="float: left; color: #c0c4cc">{{ dialog_title }}</div>
      </template>
      <el-form ref="form" :model="form">
        <el-form-item label="房型名称">
          <el-input v-model="form.pms_title" style="width: 280px"></el-input>
        </el-form-item>
        <el-form-item label="房型简称">
          <el-input v-model="form.pms_sort_title" style="width: 280px"></el-input>
        </el-form-item>
        <el-form-item label="默认价" label-width="80px">
          <span>
            <el-radio v-model="form.pms_price_type" label="0">不区分</el-radio>
            <el-radio v-model="form.pms_price_type" label="1">区分平日、周末</el-radio>
          </span>
          <div v-if="form.pms_price_type == '0'" style="
              width: 280px;
              line-height: 58px;
              margin-top: 20px;
              text-align: center;
              height: 58px;
              background: #f2f6fc;
            ">
            <span style="display: inline-block; margin-right: 10px">默认</span>
            <span style="width: 184px; display: inline-block">
              <el-input placeholder="默认价" v-model="form.pms_uniform_price" prefix-icon="el-icon-my-money">
              </el-input>
            </span>
          </div>
          <div v-if="form.pms_price_type == '1'" style="
              width: 280px;
              line-height: 58px;
              margin-top: 20px;
              text-align: center;
              height: 120px;
              background: #f2f6fc;
            ">
            <span style="display: inline-block; margin-right: 10px">默认</span>
            <span style="width: 184px; display: inline-block">
              <el-input placeholder="默认价" v-model="form.pms_weekday_price" prefix-icon="el-icon-my-money">
              </el-input>
            </span>
            <div>
              <span style="display: inline-block; margin-right: 10px">周末</span>
              <span style="width: 184px; display: inline-block">
                <el-input placeholder="周末价" v-model="form.pms_weekend_price" prefix-icon="el-icon-my-money">
                </el-input>
              </span>
            </div>
          </div>
        </el-form-item>

        <el-form-item style="margin-top: 20px" label="房间数量">
          <span style="width: 84px; display: inline-block; margin-left: 10px">
            <el-input v-model="roomType_num" oninput="value=value.replace(/[^\d]/g,'')" @blur="RoomBlur($event)">
            </el-input>
            <span v-if="roomType_num > 100" style="color: red; font-size: 12px">范围只能1-100</span>
          </span>
          <span style="color: #c0c4cc; font-size: 12px; margin-left: 20px">鼠标失去焦点后触发</span>
        </el-form-item>
        <el-form-item label="房间号">
          <div class="room">
            <div class="input" style="width: 84px" v-for="(item, index) in form.hotel_room_num" :key="index">
              <el-input style="position: relative" @blur="moveAdd(item)" v-model="form.hotel_room_num[index].room_num">
              </el-input>
              <el-button class="absolute pointer flex-center-center" type="text" @click="delRoom(item, index)"><i
                  class="el-icon-error" style="line-height: 1.1; color: red"></i></el-button>
            </div>
          </div>
        </el-form-item>
        <div style="margin-left: 60px; margin-top: 20px">
          <el-button type="text" @click="addRoom"> +新增房间 </el-button>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <div class="button">
          <el-button @click="cancel" style="">取 消</el-button>
          <el-button type="primary" @click="AddRoomType">确 定</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  AddRoom,
  GetRooms,
  GetAllRoomType,
  RoomTypeSetting,
  DelRoomType,
} from '@/api/hotel'
export default {
  pms_sort_title: 'ListAccount',
  computed: {
    value2: {
      get() {
        let value = this.roomType_num.replace(/[^\d]+/g, '')
        if ((value = 100)) {
          return 100
        } else {
          return value
        }
      },
      set(val) {
        this.value1 = val
      },
    },
    // 表格最大高度
    tableMaxHeight() {
      return this.maxHeight + 'px';
    }
  },
  watch: {
    roomType_num(newName, oldName) {
      if (newName > 100) {
        console.log('watch')
      }
    },
  },
  data() {
    return {
      maxHeight: window.innerHeight - 430,//表格最大 高度

      item: '',
      edit_room: [],
      week: '1',
      AllRoomTypeId: [], //所有房型的ID
      AllRoom_total: [],
      addRoomArr: [
        {
          RoomNum: 201,
        },
        {
          RoomNum: 202,
        },
      ],
      centerDialogVisible: false,
      roomType_num: '', //房间数量
      dialog_title: '',
      before_form: {}, //储存修改前得form
      form: {
        hotel_id: null,
        pms_title: '', //房型名称
        pms_sort_title: '', //房型简称
        // room_theme:'', //房型主题ID
        pms_price_type: '', //价格类型 0统一价 1区分平日/周末价,
        pms_uniform_price: '', //不区分的时候价格
        pms_weekday_price: '', //平日价
        pms_weekend_price: '', //周末价
        hotel_room_num: ['201', '202'],
      },
      tableData: [],
      hotel_id: null,
      del_room: [],
      afterthought_room: [],
    }
  },
  created() {
    this.form.hotel_id = sessionStorage.getItem('hotel_id')
    this.GetAllRoomType()
    this.GetAllRoom()
  },
  mounted() {
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 移除窗口大小变化的监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 获取不同屏幕大小表格的最大高度
    handleResize() {
      // 在这里处理窗口大小变化的逻辑
      let screenHeight = window.innerHeight;
      // console.log(screenHeight, '高');
      // 425 除了表格其它元素的高度
      this.maxHeight = screenHeight - 180
      console.log(this.maxHeight, ' this.maxHeight', window.innerHeight);
    },

    RoomBlur(event) {
      if (event.currentTarget.value > 100) {
        console.log(event.currentTarget.value)
      } else {
        let for_num = event.currentTarget.value - this.form.hotel_room_num.length - 1
        for (let index = 0; index <= for_num; index++) {
          this.form.hotel_room_num.push({ room_num: '' })
        }
      }
    },
    add() {
      sessionStorage.setItem('tableData', JSON.stringify(this.tableData))
      this.dialog_title = '新增房型'
      this.centerDialogVisible = true
      this.form = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        pms_title: '', //房型名称
        pms_sort_title: '', //房型简称
        // room_theme:'', //房型主题ID
        pms_price_type: '', //价格类型 0统一价 1区分平日/周末价,
        pms_weekday_price: '', //平日价
        pms_weekend_price: '', //周末价
        hotel_room_num: [{ room_num: '' }],
      }
    },
    // 添加或者编辑
    async AddRoomType() {
      console.log(this.form.id)
      if (this.form.id == undefined) {
        console.log(this.form, '======')
        let arr = []
        this.form.hotel_room_num.forEach((item) => {
          arr.push(item.room_num)
          console.log(item.room_num)
        })
        this.form.hotel_room_num = arr

        await AddRoom(this.form).then((res) => {
          // console.log(res)
          if (res.data.message == '保存成功') {
            this.$message({
              message: res.data.message,
              type: 'success'
            });
            this.GetAllRoomType()
            this.GetAllRoom()
            this.centerDialogVisible = false
          } else if (res.data.message == "pms_uniform_price不能为空") {
            this.$message({
              message: '价格填写不能为空',
              type: 'warning'
            });
          } else if (res.data.message == "pms_weekday_price不能为空") {
            this.$message({
              message: '区分周末默认价不能为空',
              type: 'warning'
            });
            this.centerDialogVisible = false
          } if (res.data.message == "pms_weekend_price不能为空") {
            this.$message({
              message: '区分周末周末价不能为空',
              type: 'warning'
            });
            this.centerDialogVisible = false
          }
        })
      } else {
        // 添加和修改的分开
        let hotel_room_num = {
          add: this.afterthought_room,
          update: this.form.hotel_room_num,
          delete: this.del_room,
        }
        let update = []
        for (let index = 0; index < hotel_room_num.update.length; index++) {
          if (hotel_room_num.update[index].id != undefined) {
            update.push(hotel_room_num.update[index])
          }
        }
        hotel_room_num.update = update
        let data = {
          hotel_id: this.form.hotel_id,
          pms_title: this.form.pms_title,
          id: this.form.id,
          pms_sort_title: this.form.pms_sort_title,
          pms_price_type: this.form.pms_price_type,
          pms_weekday_price: this.form.pms_weekday_price,
          pms_weekend_price: this.form.pms_weekend_price,
          hotel_room_num: hotel_room_num,
        }
        console.log(data)
        await RoomTypeSetting(data, 'PUT').then((res) => {
          if (res.data.message == '保存成功') {
            console.log('保存成功')
            this.GetAllRoom()
            this.$message.success('保存成功')
            this.centerDialogVisible = false
          } else {
            this.$message.error('保存失败，请联系相关工作人员')
          }
        })
      }
    },
    addRoom() {
      this.form.hotel_room_num.push({ room_num: '' })
    },
    // 编辑房型号失去焦点后保存起来
    edit_roomNum(value, index) {
      // this.edit_room.push(value)
      // this.edit_room.splice(index, 1)
      // console.log(this.edit_room, "====this.edit_room====");
      // console.log(index, "====index====");
    },
    delRoom(item, index) {
      this.del_room.push(this.form.hotel_room_num[index])
      console.log(this.form.hotel_room_num[index], index)
      this.form.hotel_room_num.splice(index, 1)
    },
    async GetAllRoomType() {
      let data = {
        hotel_id: this.form.hotel_id,
      }
      await GetAllRoomType(data).then((res) => {
        this.AllRoomTypeId = res.data.data
        // console.log(this.AllRoomTypeId);
      })
    },
    // 获取所有房型
    GetAllRoom() {
      setTimeout(() => {
        this.tableData = []

        this.AllRoomTypeId.forEach(async (item) => {
          // console.log(item)
          let data = {
            id: item.id,
            hotel_id: this.form.hotel_id,
          }
          await GetRooms(data).then((res) => {
            let Room_num = res.data.data.hotel_room_num.length
            let roomType = res.data.data
            roomType.quantity = Room_num
            this.tableData.push(roomType)
            // console.log(Room_num)
          })
        })
        console.log(this.tableData, '=====??===')
      }, 1000)
    },
    handleEdit(index, row) {
      sessionStorage.setItem('tableData', JSON.stringify(this.tableData))

      this.dialog_title = '编辑房型'
      this.centerDialogVisible = true
      let form = row
      this.form = form
      this.del_room = []
      this.afterthought_room = []
      this.before_form = this.form
      console.log(this.tableData, '====this.form====')
      // console.log(index, row)
    },
    moveAdd(value) {
      if (value.id == undefined) {
        if (value.room_num != '') {
          // console.log(value);
          if (this.afterthought_room.indexOf(value.room_num) == -1) {
            this.afterthought_room.push(value.room_num)
          }
        }

        // 编辑，添加和修改都在一起
        // let hotel_room_num = {
        //   update: this.form.hotel_room_num,
        // }
        // hotel_room_num.update.forEach(item => {
        //   if (item.id == undefined) {
        //     // console.log(item);
        //     this.afterthought_room.push(item.room_num)
        //   }
        // })
      }
    },
    cancel() {
      console.log(123)
      // console.log(this.before_form);
      console.log(this.form === this.tableData)
      // console.log(this.tableData)
      // this.centerDialogVisible = false
    },
    async handleDelete(index, row) {
      console.log(index, row, '点击了删除房型')
      let data = {
        id: row.id,
      }
      await DelRoomType(data).then((res) => {
        console.log(res)
        if (res.data.message == '删除成功') {
          this.$message.success('删除成功')
          this.GetAllRoom()
        }
      })
    },
    closed() {
      console.log('关闭')
      if (JSON.parse(sessionStorage.getItem('tableData')) != undefined) {
        this.tableData = JSON.parse(sessionStorage.getItem('tableData'))
      }

      this.centerDialogVisible = false
      // this.GetAllRoom()
    },
  },
}
</script>

<style lang="scss" scoped>
.content {
  .overflow-auto {
    .right {
      width: calc(100% - 195px);
      padding: 20px;

      .add {
        float: right;

      }
    }

    .table {
      height: calc(100% - 100px);

      span {
        display: inline-block;
      }
    }
  }

  .el-dialog {
    .button {
      float: right;
    }
  }
}

::v-deep.room {
  display: flex;
  flex-wrap: wrap;
  // width: 85%;
  padding-left: 25px;

  .input {
    position: relative;
    margin-right: 10px;
    margin-bottom: 20px;
  }

  .el-button {
    position: absolute;
    right: -8px;
    top: -20px;
  }
}

::v-deep .el-icon-my-money {
  background: url("../../../../assets/images/￥.png") center center no-repeat;
  background-size: 12px;
}
</style>
